<?php

class BoxtabsPage extends BaseAdminPage {

	/**
	 * Az aktuális doboz fül doboz tartalom listájának pillanatnyi állapota (nem biztos, hogy egyezik a db-vel!)
	 */
	private $allBoxContentListRecords;

	/**
	 * A szerkesztés alatt álló doboz azonosítója. 
	 */
	private $boxId;

	/**
	 * A szerkesztés alatt álló doboz fül azonosítója. 
	 */
	private $editedBoxTabId;

	/**
	 * A szerkesztés alatt álló doboz tartalom lista. 
	 */
	private $editedBoxContentListId;

	/**
	 * Újonnan létrehozott doboz fül szerkesztése folyik-e.
	 */
	private $isnew;

	/**
	 * Doboz tartalom lista típusok.
	 */
	private $boxContentListTypeArray;

	/**
	 * Doboz tartalom lista objektum típusok.
	 */
	private $boxContentListClassArray;
	
	function BoxtabsPage() {
		parent::BaseAdminPage("BoxtabsPage");
	}

	function enterPage()
	{
		parent::enterPage();

		$this->boxContentListTypeArray = ConstHandler::get("BOXCONTENTLIST_TYPES");
		$_SESSION["_boxContentListTypeArray"] = $this->boxContentListTypeArray;

		$this->boxContentListClassArray = ConstHandler::get("BOXCONTENTLIST_CLASSES");
		$_SESSION["_boxContentListClassArray"] = $this->boxContentListClassArray;
		
		$boxId = FunctionLibrary::getGetValue("boxid");
		$_SESSION['_bxt_boxId'] = $boxId;

		// hack: editálja az alapértelmezett (és egyetlen) doboz fület
		$defaultBoxTab =& AdminDBHelper::getDefaultBoxTab($boxId);
		$_SESSION['_bxt_boxTabId'] = $defaultBoxTab['id'];

		$boxContentListRecords =& AdminDBHelper::getDefaultBoxContentLists($boxId);
		$this->setBoxContentListRecords($boxContentListRecords);

		$langcode = AdminBase::getCurrentEditlang();
		$boxContentsTmp = AdminDBHelper::getBoxContents($langcode);
		$boxContents = array();
		foreach ($boxContentsTmp as $boxContent) {
			$boxContents[$boxContent['id']] = $boxContent['worktitle'];
		}
		// $_SESSION['_bxt_boxContents'] = $boxContents;

		// definiáljuk a form elemeit
		FormUtil::addForm("boxtab");
		FormUtil::addFormElement("boxtab", new FormElementInfo("id", "text", null));
		FormUtil::addFormElement("boxtab", new FormElementInfo("label", "text", null));

		FormUtil::addForm("boxtabcontentlist");
		FormUtil::addFormElement("boxtabcontentlist", new FormElementInfo("id", "text", null));
		FormUtil::addFormElement("boxtabcontentlist", new FormElementInfo("name", "text", null));
		FormUtil::addFormElement("boxtabcontentlist", 
			new FormElementInfo("class", 
					"select", 
					null, 
					array("arrayType"=>"simpleArray", "array" => $this->boxContentListClassArray, "translateLabels" => true)));
		FormUtil::addFormElement("boxtabcontentlist", 
			new FormElementInfo("type", 
					"select", 
					null, 
					array("arrayType"=>"simpleArray", "array" => $this->boxContentListTypeArray, "translateLabels" => true)));
		FormUtil::addFormElement("boxtabcontentlist", new FormElementInfo("manualstep", "checkbox", null));
		FormUtil::addFormElement("boxtabcontentlist", new FormElementInfo("autostep", "text", null));
		FormUtil::addFormElement("boxtabcontentlist", 
			new FormElementInfo("box_article_ids", 
					"select", 
					null, 
					array("arrayType"=>"simpleArray", "array"=>$boxContents)));
		FormUtil::addFormElement("boxtabcontentlist", new FormElementInfo("sizemin", "text", null));
		FormUtil::addFormElement("boxtabcontentlist", new FormElementInfo("sizemax", "text", null));
		
	}


	function leavePage()
	{
		parent::leavePage();

		$this->_init();

		FormUtil::removeAllForms();

		unset($_SESSION['_bxt_boxContentListRecords']);
		unset($_SESSION["_boxContentListTypeArray"]);
		unset($_SESSION["_boxContentListClassArray"]);
		unset($_SESSION["_bxt_boxContentListId"]);
		unset($_SESSION["_bxt_boxTabId"]);
		unset($_SESSION["_bxt_isnew"]);
		unset($_SESSION['_bxt_boxId']);
	}

	/**
	 * Feltölti session-ből az aktuális működési változókat
	 */
	protected function _init()
	{
		$this->editedBoxContentListId = FunctionLibrary::getSessionValue("_bxt_boxContentListId", null);
		$this->editedBoxTabId = FunctionLibrary::getSessionValue("_bxt_boxTabId", null);
		$this->boxId = FunctionLibrary::getSessionValue('_bxt_boxId', null);
		$this->boxContentListTypeArray = FunctionLibrary::getSessionValue("_boxContentListTypeArray");
		$this->boxContentListClassArray = FunctionLibrary::getSessionValue("_boxContentListClassArray");
		$this->allBoxContentListRecords = FunctionLibrary::getSessionValue("_bxt_boxContentListRecords");

		$this->isnew = FunctionLibrary::getGetValue("isnew");
		if (empty($this->isnew)) {
			$this->isnew = FunctionLibrary::getSessionValue("_bxt_isnew", "0");
		} else {
			$_SESSION["_bxt_isnew"] = $this->isnew;
		}
	}

	protected function getListPageLink()
	{
		return HydraLinkProvider::getLink('boxtabs', array('boxid'=>$this->boxId));
	}

	protected function setBoxContentListRecords($boxContentListRecords) {
		$_SESSION["_bxt_boxContentListRecords"] = $boxContentListRecords;
	}

	protected function getBoxContentListFromSession($boxContentListId) {
		for ($i = 0; $i < count($this->allBoxContentListRecords); $i++) {
			if ($this->allBoxContentListRecords[$i]['id'] == $boxContentListId) {
				return $i;
			}
		}
		throw new MissingTableRowException(TextHandler::getText('bxt_err_contentlistnotfound'));
	}
	

	public function serveRequest()
	{
		parent::serveRequest();
		
		$this->_init();

		$tpl = BaseAdminPage::loadTemplateFile(BOXTABS_TEMPLATE);
		TextHandler::insertTextsIntoTemplate($tpl, null, "bxt_");
		$tpl->setVariable('app_root_url', APP_ROOT_URL);
		$tpl->setVariable('admin_tbl_opers', TextHandler::getText("admin_tbl_opers"));
		$tpl->setVariable('form_action_addboxtab', HydraLinkProvider::getLink('addBoxTab'));
		$tpl->setVariable('form_action_modboxtab', HydraLinkProvider::getLink('updateBoxTab'));
		$tpl->setVariable('form_action_addboxcontentlist', HydraLinkProvider::getLink('addBoxContentList'));
		
		// felnyaljuk a rekordokat
		$allBoxTabRecords =& SiteDBHelper::getBoxTabs($this->boxId);
		if(is_null($allBoxTabRecords))
		{
			// suxxx!
			handleError(TextHandler::getText('err_readrecordsfailed'));
			$tpl->replaceBlock('boxtab', ' ', false);
			$tpl->touchBlock('boxtab');
		}
		else
		{
			$action = FunctionLibrary::getGetOrPostValue('action');
			if($action)
			{
				$action = 'action_'.$action;
				$this->$action();
			}

			// megvannak a rekordok!
			if(count($allBoxTabRecords) == 0)
			{
				$tpl->replaceBlock('tabheader', ' ', false);
				$tpl->touchBlock('tabheader');
			}
			else
			{
				$warnMessages = array();
				$countBoxTabRecords = count($allBoxTabRecords);
				$i = 1;
				foreach($allBoxTabRecords as $boxTabRecord)
				{
					if ($boxTabRecord['id'] == $this->editedBoxTabId) {
						// doboz tartalmak
						$editBoxTabTpl = BaseAdminPage::loadTemplateFile(EDITBOXTAB_TEMPLATE);
						TextHandler::insertTextsIntoTemplate($editBoxTabTpl, null, "bxt_");
						TextHandler::insertTextsIntoTemplate($editBoxTabTpl, null, "but_");
						// a saved form instance-ból töltjük fel a sablon értékeit
						FormUtil::insertFormValuesToTemplate("boxtab", $editBoxTabTpl, "saved");
						if (count($this->allBoxContentListRecords) == 0) {
							$editBoxTabTpl->setVariable('hiddenClass', 'empty-box-content-list');
						}
						$editBoxTabTpl->setVariable('id', $boxTabRecord['id']);
						$editBoxTabTpl->setVariable('label', $boxTabRecord['label']);
						$editBoxTabTpl->setVariable('link_editboxtab', HydraLinkProvider::getLink('editBoxTab', array("tabid"=>$boxTabRecord['id'], "isnew"=>"0")));
						$editBoxTabTpl->setVariable('link_moveForward', HydraLinkProvider::getLink('moveBoxTabForward', array("tabid"=>$boxTabRecord['id'])));
						$editBoxTabTpl->setVariable('link_moveBackward', HydraLinkProvider::getLink('moveBoxTabBackward', array("tabid"=>$boxTabRecord['id'])));
						$editBoxTabTpl->setVariable('link_delboxtab', HydraLinkProvider::getLink('delBoxTab', array("tabid"=>$boxTabRecord['id'])));
						$editBoxTabTpl->setVariable('form_action_addboxcontentlist', HydraLinkProvider::getLink('addBoxContentList'));
						$editBoxTabTpl->setVariable('cancelLink', HydraLinkProvider::getLink('cancelBoxTab'));
						$editBoxTabTpl->setVariable('app_root_url', APP_ROOT_URL);
						$editBoxTabTpl->setVariable('admin_tbl_opers', TextHandler::getText("admin_tbl_opers"));

						foreach($this->allBoxContentListRecords as $boxContentList) {
							if (! isset($boxContentList['isnew']) || ! isset($boxContentList['isdeleted'])) {
								if ($this->editedBoxContentListId == $boxContentList['id'] && ! isset($boxContentList['isdeleted'])) {
									$editedBoxContentListTpl = BaseAdminPage::loadTemplateFile(EDITBOXTABLIST_TEMPLATE);
									TextHandler::insertTextsIntoTemplate($editedBoxContentListTpl, null, "bxt_");
									TextHandler::insertTextsIntoTemplate($editedBoxContentListTpl, null, "but_");
									// a saved form instance-ból töltjük fel a sablon értékeit
									FormUtil::insertFormValuesToTemplate("boxtabcontentlist", $editedBoxContentListTpl, "saved");

									$editedBoxContentListTpl->setVariable('app_root_url', APP_ROOT_URL);
									$editedBoxContentListTpl->setVariable('form_action_boxcontentlist', HydraLinkProvider::getLink('updateBoxContentList'));
									$editedBoxContentListTpl->setVariable('cancelLink', HydraLinkProvider::getLink('cancelBoxContentList'));
									$editedBoxContentListTpl->setVariable("id", $boxContentList['id']);
									$editedBoxContentListTpl->setVariable("name", $boxContentList['name']);
									$editedBoxContentListTpl->setVariable('link_delboxtablist', HydraLinkProvider::getLink('delBoxContentList', array('contentlistid' => $boxContentList['id'])));
									
									$this->insertTDClassVariablesToTemplate($editedBoxContentListTpl, $boxContentList);									
									
									$boxContentListContent = $editedBoxContentListTpl->get();
								} else {
									$rawBoxContentListTpl = BaseAdminPage::loadTemplateFile(RAWBOXTABLIST_TEMPLATE);
									TextHandler::insertTextsIntoTemplate($rawBoxContentListTpl, null, "bxt_");
									$rawBoxContentListTpl->setVariable('app_root_url', APP_ROOT_URL);
									$rawBoxContentListTpl->setVariable("id", $boxContentList['id']);
									$rawBoxContentListTpl->setVariable("name", $boxContentList['name']);
									// megjelenített típus összerakása
									$dispType = TextHandler::getText("bxt_list_class_".$boxContentList['class']);
									if($boxContentList['class'] == "BoxContentList")
										$dispType .= ", ".TextHandler::getText($this->boxContentListTypeArray[$boxContentList['type']]);
									$rawBoxContentListTpl->setVariable("type", $dispType);
									$rawBoxContentListTpl->setVariable("size", $boxContentList['sizemin'].' - '.$boxContentList['sizemax']);
									$rawBoxContentListTpl->setVariable('link_editboxtablist', HydraLinkProvider::getLink('editBoxContentList', array('contentlistid' => $boxContentList['id'])));
									$rawBoxContentListTpl->setVariable('link_delboxtablist', HydraLinkProvider::getLink('delBoxContentList', array('contentlistid' => $boxContentList['id'])));
									$rawBoxContentListTpl->setVariable('link_makeboxtablistdefault', HydraLinkProvider::getLink('makeBoxContentListDefault', array('contentlistid' => $boxContentList['id'])));

									$this->insertTDClassVariablesToTemplate($rawBoxContentListTpl, $boxContentList);									

									$boxContentListContent = $rawBoxContentListTpl->get();
								}
								$tmpWarnMessages = BoxContentList::checkRecord($boxContentList, null);
								if (!is_null($tmpWarnMessages)) {
									$warnMessages = FunctionLibrary::arrayConcatenate($warnMessages, $tmpWarnMessages);
								}
	
								$editBoxTabTpl->setCurrentBlock('boxcontentlist');
								$editBoxTabTpl->setVariable('boxcontentlist_content', $boxContentListContent);
								$editBoxTabTpl->parseCurrentBlock();
							}
						}

						$boxTabContent = $editBoxTabTpl->get();
					} else {
						$rawBoxTabTpl = BaseAdminPage::loadTemplateFile(RAWBOXTAB_TEMPLATE);
						TextHandler::insertTextsIntoTemplate($rawBoxTabTpl, null, "bxt_");
						$rawBoxTabTpl->setVariable('id', $boxTabRecord['id']);
						$rawBoxTabTpl->setVariable('label', $boxTabRecord['label']);
						$rawBoxTabTpl->setVariable('link_editboxtab', HydraLinkProvider::getLink('editBoxTab', array("tabid"=>$boxTabRecord['id'], "isnew"=>"0")));
						$rawBoxTabTpl->setVariable('link_moveForward', HydraLinkProvider::getLink('moveBoxTabForward', array("tabid"=>$boxTabRecord['id'])));
						if ($i == 1) {
							$rawBoxTabTpl->setVariable("hideForwardLink", "class=\"hiddenLink\" onclick=\"return false\"");
						} else {
							$rawBoxTabTpl->setVariable("hideForwardLink", "");
						}
						$rawBoxTabTpl->setVariable('link_moveBackward', HydraLinkProvider::getLink('moveBoxTabBackward', array("tabid"=>$boxTabRecord['id'])));
						if ($countBoxTabRecords == $i) {
							$rawBoxTabTpl->setVariable("hideBackwardLink", "class=\"hiddenLink\" onclick=\"return false\"");
						} else {
							$rawBoxTabTpl->setVariable("hideBackwardLink", "");
						}
						$rawBoxTabTpl->setVariable('link_makeDefault', HydraLinkProvider::getLink('makeBoxTabDefault', array("tabid"=>$boxTabRecord['id'])));
						$rawBoxTabTpl->setVariable('link_delboxtab', HydraLinkProvider::getLink('delBoxTab', array("tabid"=>$boxTabRecord['id'])));
						$rawBoxTabTpl->setVariable('app_root_url', APP_ROOT_URL);
						if ($boxTabRecord['isdefault'] == 't') {
							$rawBoxTabTpl->setVariable("trclass", 'class="default_box_tab"');
						} else {
							$rawBoxTabTpl->setVariable("trclass", "");
						}

						$boxTabContent = $rawBoxTabTpl->get();
					}
					$tpl->setCurrentBlock('boxtab');
					$tpl->setVariable('box_tab_content', $boxTabContent);
					$tpl->parseCurrentBlock();
					$i++;
				}
				$tpl->setVariable("form_action", HydraLinkProvider::getLink('updateBoxTab', array()));
				$tpl->setVariable("admin_tbl_opers", TextHandler::getText("admin_tbl_opers"));
				$tpl->setVariable("but_save", TextHandler::getText("but_save"));
				$tpl->setVariable("but_cancel", TextHandler::getText("but_cancel"));
				$tpl->setVariable("but_add", TextHandler::getText("but_add"));
				$tpl->setVariable("link_makeDefault", HydraLinkProvider::getLink('makeBoxTabDefault', array()));
				// a saved form instance-ból töltjük fel a sablon értékeit
				FormUtil::insertFormValuesToTemplate("boxtab", $tpl, "saved");
			}
			$tpl->parseCurrentBlock();
		}
		if (count($warnMessages) > 0) {
			handleWarning(TextHandler::getParsedText('bxt_warn_incomplete_boxcontentlists', array('warnings'=>TextUtil::arrayToHtmlList($warnMessages))), null, null);
		}
			
		return $tpl->get();
	}
	
	
	private function insertTDClassVariablesToTemplate($tpl, $boxContentList)
	{
		if (isset($boxContentList['isdeleted'])) {
			$tpl->setVariable('tdclass', 'deleted_box_content_list');
		} else if (isset($boxContentList['isnew'])) {
			$tdClass = 'new_box_content_list';
			if ($boxContentList['isdefault'] == 't') {
				$tdClass .= ' default_box_content_list';
			}
			$tpl->setVariable('tdclass', $tdClass);
		} else if (isset($boxContentList['ismodified'])) {
			$tpl->setVariable('tdclass', 'modified_box_content_list');
		} else if ($boxContentList['isdefault'] == 't') {
			//$tpl->setVariable('tdclass', 'default_box_content_list');
		} else {
			$tpl->setVariable('tdclass', '');
		}
		if ($boxContentList['isdefault'] == 't') {
			$tpl->setVariable('defclass', 'default_box_content_list');
		}
		else
		{
			$tpl->setVariable('defclass', '');
		}
	}

	/**
	 * Új doboz fül rekord hozzáadása
	 */
	private function action_addBoxTab()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		try {
			$label = FunctionLibrary::getPostValue('label');
			if (empty($label)) {
				$errorStrings = array(TextHandler::getText('bxt_err_label_empty'));
				handleError(TextHandler::getParsedText('bxt_err_add_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
			} else {
				$boxTabId = AdminDBHelper::addBoxTab($this->boxId, $label);
	
				$editLink = HydraLinkProvider::getLink('editBoxTab', array('tabid'=>$boxTabId, "isnew"=>"1"));
	
				// ha sikeres volt, akkor át is lépünk a szerkesztő oldalra, de azzal amegjegyzéssel h ez egy új doboz
				handleSuccess(TextHandler::getText("bxt_added"), $editLink);
				exit();
			}

		} catch (Exception $e) {
			$logErrorString = "adding box tab, box_id=".$this->boxId." failed";
			$errorStrings = array($e->getMessage());
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_add_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	private function action_editBoxTab() {
		$this->editedBoxTabId = FunctionLibrary::getGetOrPostValue("tabid");
		// csinálnunk kell neki egy form instance-t!
		try {
			$boxTabRecord = AdminDBHelper::getBoxTab($this->editedBoxTabId) ;

			if(!is_null($boxTabRecord))
			{
				// ez most kinyílt, hama csinálunk neki egy form instance-t!
				FormUtil::addFormInstanceIfNotExists("boxtab", "saved");
				FormUtil::fillFormValuesFromObject("boxtab", $boxTabRecord, "saved");
				$_SESSION["_bxt_boxTabId"] = $this->editedBoxTabId;

				$boxContentListRecords =& SiteDBHelper::getBoxContentLists($this->editedBoxTabId);
				$this->setBoxContentListRecords($boxContentListRecords);
				$this->allBoxContentListRecords = $boxContentListRecords;

				return;
			} else {
				$errorStrings = array("parameter error");
				$logErrorString = "failed to get box_tab record id=".$this->editedBoxTabId." due to parameter error!";
			}
		} catch (Exception $e) {
			// db hiba!

			$errorStrings = array($e->getMessage());
			$logErrorString = "failed to get boxtab record id=$elementId due to db error!";
		}
		Log::error('following errors occured during operation:'.$logErrorString);
			
		handleError(TextHandler::getParsedText('err_op_failed', array("errors"=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
		exit();
	}

	private function action_makeBoxTabDefault() {
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		$id = FunctionLibrary::getGetOrPostValue('tabid');
		try {
			if (! is_numeric($id)) {
				$logErrorString = "make box tab default id=$id failed: bad parameter";
				$errorStrings = array(TextHandler::getText('bxt_err_boxtab_notfound'));
			} else {
				$record =& AdminDBHelper::getBoxTab($id);

				if (empty($record)) {
					$logErrorString = "make box tab default id=$id failed: box tab not found";
					$errorStrings = array(TextHandler::getText('bxt_err_boxtab_notfound'));
				} else {
					AdminDBHelper::makeBoxTabDefault($id, $this->boxId);
					
					// ha sikeres volt, akkor újraolvas
					handleSuccess(TextHandler::getText("bxt_madedefault"), $this->getListPageLink());
					exit();
				}
			}
		} catch (Exception $e) {
			$logErrorString = "make box tab default id=$id failed";
			$errorStrings = array($e->getMessage());
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_makedefault_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	/**
	 * Törli a doboz fület.
	 */
	private function action_delBoxTab()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;
			
		$id = FunctionLibrary::getGetOrPostValue('tabid');

		if(!is_null($id) && TextUtil::isStringInteger($id))
		{
			$id = intval($id);

			try {
				$record =& AdminDBHelper::delBoxTab($id);

				handleSuccess(TextHandler::getParsedText("bxt_removed", array('label' => $record['label'])), $this->getListPageLink());
				exit();
			} catch (MissingTableRowException $e) {
				$logErrorString = "removing box_tab id=$id failed: ".$e->getMessage();
				$errorStrings = array(TextHandler::getText('bxt_err_boxtab_notfound'));
			} catch (Exception $e) {
				$logErrorString = "removing box_tab id=$id failed: ".$e->getMessage();
				$errorStrings = array($e->getMessage());
			}
		}
		else
		{
			$logErrorString = "required request parameter 'id' is missing or malformed";
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_delete_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	/**
	 * Menti a doboz fül módosításait
	 */
	private function action_updateBoxTab()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		// töltsük be a form értékeket!
		/* most skipped
		FormUtil::fillFormValuesFromRequest("boxtab", "saved");
		$boxTabRecordFromForm = FormUtil::getFormValues("boxtab", "saved");
		$boxTabRecord = array(
			'id' => $this->editedBoxTabId,
			'label' => $boxTabRecordFromForm['label']
		);
		$boxTabRecordId = $boxTabRecord['id'];
		*/
		$boxTabRecordId = $this->editedBoxTabId;
		if(!is_null($boxTabRecordId))
		{
			// ok, save it back!
			try {
				AdminDBHelper::modBoxTab($boxTabRecordId, $this->allBoxContentListRecords);

				$boxContentListRecords =& SiteDBHelper::getBoxContentLists($this->editedBoxTabId);
				$this->setBoxContentListRecords($boxContentListRecords);

				unset($_SESSION["_bxt_boxTabId"]);

				// ok, done!
				handleSuccess(TextHandler::getText("bxt_modified"), HydraLinkProvider::getLink("boxes"));
				exit();
			} catch (MissingTableRowException $e2) {
				$logErrorString = "failed to update box tab record id=$boxTabRecordId in db!";
				$errorStrings = array(TextHandler::getText('bx_err_boxnotfound'));
			} catch (Exception $e2) {
				$errorStrings = array($e2->getMessage());
				$logErrorString = "failed to update box tab record id=$boxTabRecordId in db!";
			}

		}
		else
		{
			$errorStrings = array(TextHandler::getText('bxt_err_boxtab_notfound'));
			$logErrorString = "failed to find box tab record id=$boxTabRecordId in db, probably deleted";
		}

		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_save_failed', array("errors"=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
		exit();
	}

	/**
	 * Doboz fül mozgatása
	 * 
	 * @param boolean $isForward Ha igaz, akkor előre (csökken a sorszáma) mozgatja.
	 */
	private function action_move($isForward)
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;
			
		$id = FunctionLibrary::getGetValue("tabid");

		if(!is_null($id) && TextUtil::isStringInteger($id))
		{
			$id = intval($id);

			// szedjük vissza a rekordot! ez tömböt ad, tudod!
			$boxTabRecord = AdminDBHelper::getBoxTab($id);
			if(is_null($boxTabRecord))
			{
				// nincs mit törölni!
				handleError(TextHandler::getText('bxt_err_boxtab_notfound'), $this->getListPageLink());
				exit();
			}

			try {
				AdminDBHelper::moveBoxTab($boxTabRecord, $isForward);

				handleSuccess(TextHandler::getParsedText("bxt_moved", array('label' => $boxTabRecord['label'])), $this->getListPageLink());
				exit();
			} catch (Exception $e) {
				$logErrorString = "moving box_tab id=$id failed: ".$e->getMessage();
				$errorStrings = array($e->getMessage());
			}
		}
		else
		{
			$logErrorString = "required request parameter 'id' is missing or malformed";
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_move_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	private function action_moveBoxTabForward() {
		$this->action_move(true);
	}

	private function action_moveBoxTabBackward() {
		$this->action_move(false);
	}

	/**
	 * Cancel
	 */
	private function action_cancelBoxTab()
	{
		// session ürítése
		unset($_SESSION["_bxt_boxTabId"]);
		unset($_SESSION['_bxt_boxContentListRecords']);
		FormUtil::removeFormInstanceIfExists("boxtab", "saved");

		// visszalépünk a listára
		handleSuccess(null, HydraLinkProvider::getLink("boxes"));
		exit();
	}

	/**
	 * Új doboz tartalom lista rekord hozzáadása
	 */
	private function action_addBoxContentList()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		try {
			$name = FunctionLibrary::getGetOrPostValue('name');
			if (empty($name)) {
				$errorStrings = array(TextHandler::getText('bxt_err_list_name_empty'));
			 	handleError(TextHandler::getParsedText('bxt_err_list_add_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
			} else {
				$boxContentListRecord =& AdminDBHelper::generateBoxContentList($this->editedBoxTabId, $name);
				if (count($this->allBoxContentListRecords) == 0) {
					$boxContentListRecord['isdefault'] = 't';
				}
				array_push($this->allBoxContentListRecords, $boxContentListRecord);
				$this->setBoxContentListRecords($this->allBoxContentListRecords);
	
				$editLink = HydraLinkProvider::getLink('editBoxContentList', array('contentlistid'=>$boxContentListRecord['id'], "isnew"=>"1"));
	
				// ha sikeres volt, akkor át is lépünk a szerkesztő oldalra, de azzal amegjegyzéssel h ez egy új doboz
				handleSuccess(TextHandler::getText("bxt_added"), $editLink);
				exit();
			}

		} catch (Exception $e) {
			$logErrorString = "adding box_content_list, box_tab_id=".$this->boxTabId." failed";
			$errorStrings = array($e->getMessage());
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_list_add_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	private function action_editBoxContentList() {
		$this->editedBoxContentListId = FunctionLibrary::getGetOrPostValue("contentlistid");
		// csinálnunk kell neki egy form instance-t!
		try {
			$boxContentListRecordIndex = $this->getBoxContentListFromSession($this->editedBoxContentListId);
			$boxContentListRecord = $this->allBoxContentListRecords[$boxContentListRecordIndex];

			if(empty($boxContentListRecord['attributes']))
				$attributes = array();
			else
				$attributes = unserialize($boxContentListRecord['attributes']);
			foreach($attributes as $key => $value) {
				$boxContentListRecord[$key] = $value;
				
				// ez egy csúnya hack, de most hirtelen ez van...
				if($key == CategoryBoxContentList::ATTR_CAT_TYPE) {
					$catId = FunctionLibrary::getArrayValue($attributes, CategoryBoxContentList::ATTR_CAT_ID, null);
					if(is_null($catId))
						$catId = "root";
					$catType = $value;
					$boxContentListRecord['category'] = $catId . "_" . $catType;
				}
				elseif($key == CategoryBoxContentList::ATTR_DISPLAY) {
					$boxContentListRecord['display'] = FunctionLibrary::getArrayValue($attributes, CategoryBoxContentList::ATTR_DISPLAY, null);
				}
			}
			
			// ez most kinyílt, hama csinálunk neki egy form instance-t!
			FormUtil::addFormInstanceIfNotExists("boxtabcontentlist", "saved");
			FormUtil::fillFormValuesFromObject("boxtabcontentlist", $boxContentListRecord, "saved");
			$_SESSION["_bxt_boxContentListId"] = $this->editedBoxContentListId;
			return;
		} catch (Exception $e) {
			// db hiba!
			$errorStrings = array($e->getMessage());
			$logErrorString = "failed to get box_content_list record id=".$this->editedBoxContentListId." due to db error!";
		}
		Log::error('following errors occured during operation:'.$logErrorString);
			
		handleError(TextHandler::getParsedText('err_op_failed', array("errors"=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
		exit();
	}

	private function action_delBoxContentList() {
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;
			
		$id = FunctionLibrary::getGetValue('contentlistid');

		if(!is_null($id) && TextUtil::isStringInteger($id))
		{
			try {
				$boxContentListRecordIndex = $this->getBoxContentListFromSession($id);
				$boxContentListRecord = $this->allBoxContentListRecords[$boxContentListRecordIndex];
				$boxContentListRecord['isdeleted'] = true;
				$this->allBoxContentListRecords[$boxContentListRecordIndex] = $boxContentListRecord;
				$this->setBoxContentListRecords($this->allBoxContentListRecords);
				handleSuccess(TextHandler::getText("bxt_list_removed"), $this->getListPageLink());
				exit();
			} catch (Exception $e) {
				$logErrorString = "removing box id=$id failed: ".$e->getMessage();
				$errorStrings = array($e->getMessage());
			}
		}
		else
		{
			$logErrorString = "required request parameter 'id' is missing or malformed";
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bx_err_remove_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	private function action_makeBoxContentListDefault() {
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		try {
			$id = FunctionLibrary::getGetValue('contentlistid');
	
			if(!is_null($id) && TextUtil::isStringInteger($id))
			{
				for ($i = 0; $i < count($this->allBoxContentListRecords); $i++) {
					if ($this->allBoxContentListRecords[$i]['id'] == $id) {
						$this->allBoxContentListRecords[$i]['isdefault'] = DBUtil::encodeBooleanFieldValue(true);
					} else if ($this->allBoxContentListRecords[$i]['isdefault']) {
						$this->allBoxContentListRecords[$i]['isdefault'] = DBUtil::encodeBooleanFieldValue(false);
					}
					$this->allBoxContentListRecords[$i]['ismodified'] = true;
				}
				$this->setBoxContentListRecords($this->allBoxContentListRecords);
	
				// ha sikeres volt, akkor újraolvas
				handleSuccess(TextHandler::getText("bxt_list_madedefault"), $this->getListPageLink());
				exit();
			} else {
				$errorStrings = array(TextHandler::getText("bxt_err_contentlistnotfound"));
				handleError(TextHandler::getParsedText('bxt_err_contentlistmakedefault_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
			}

		} catch (Exception $e) {
			$logErrorString = "make box_content_list default id=".$this->editedBoxContentListId." failed";
			$errorStrings = array($e->getMessage());
		}
			
		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_contentlistmakedefault_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
	}

	/**
	 * Menti a doboz tartalom lista módosításait.
	 */
	private function action_updateBoxContentList()
	{
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		// töltsük be a form értékeket!
		FormUtil::fillFormValuesFromRequest("boxtabcontentlist", "saved");
		$boxContentListRecordFromForm = FormUtil::getFormValues("boxtabcontentlist", "saved");
		$boxContentListRecordId = $boxContentListRecordFromForm['id'];
		// ami numerikus, és lehet üres azt nem hagyhatjuk üres stringen!!!
		if(empty($boxContentListRecordFromForm['sizemin']))
			$boxContentListRecordFromForm['sizemin'] = null;
		if(empty($boxContentListRecordFromForm['sizemax']))
			$boxContentListRecordFromForm['sizemax'] = null;
		if(empty($boxContentListRecordFromForm['autostep']))
			$boxContentListRecordFromForm['autostep'] = null;
		/*
		if(empty($boxContentListRecordFromForm['bPerPage']))
			$boxContentListRecordFromForm['bPerPage'] = null;
		if(empty($boxContentListRecordFromForm['category']))
			$boxContentListRecordFromForm['category'] = null;
		if(empty($boxContentListRecordFromForm['display']))
			$boxContentListRecordFromForm['display'] = null;
		*/
			
		if(!is_null($boxContentListRecordId))
		{
			if($boxContentListRecordFromForm['class'] == "BoxContentList")
			{
				if (is_null($boxContentListRecordFromForm['box_article_ids'])) {
					handleError(TextHandler::getText('bxt_err_list_list_empty'), $this->getListPageLink());
				}
				if ($boxContentListRecordFromForm['type'] == BOXCONTENTLIST_TYPE_FIXED) {
					// menual selection
					$boxContentListRecordFromForm['sizemin'] = null;
					$boxContentListRecordFromForm['sizemax'] = null;
				} else {
					// auto selection
					if (empty($boxContentListRecordFromForm['sizemin']) || empty($boxContentListRecordFromForm['sizemax'])) {
						handleError(TextHandler::getText('bxt_err_list_size_empty'), $this->getListPageLink());
					} else if (! is_numeric($boxContentListRecordFromForm['sizemin']) || ! is_numeric($boxContentListRecordFromForm['sizemax'])) {
						handleError(TextHandler::getText('bxt_err_list_size_formaterror'), $this->getListPageLink());
					} else if (intval($boxContentListRecordFromForm['sizemin']) < 1 || intval($boxContentListRecordFromForm['sizemax']) < 1) {
						handleError(TextHandler::getText('bxt_err_list_size_formaterror'), $this->getListPageLink());
					} else if (intval($boxContentListRecordFromForm['sizemin']) > intval($boxContentListRecordFromForm['sizemax'])) {
						handleError(TextHandler::getText('bxt_err_list_size_mingreaterthanmax'), $this->getListPageLink());
					} else if (! empty($boxContentListRecordFromForm['autostep']) && ! is_numeric($boxContentListRecordFromForm['autostep'])) {
						handleError(TextHandler::getText('bxt_err_list_autostep_formaterror'), $this->getListPageLink());
					}
				}
				
				//$boxContentListRecordFromForm['bPerPage'] = null;
				//$boxContentListRecordFromForm['category'] = null;
				//$boxContentListRecordFromForm['display'] = null;
				
			}
			/*
			elseif($boxContentListRecordFromForm['class'] == "BrandBoxContentList")
			{
				//if (empty($boxContentListRecordFromForm['year_to_list']) || !is_numeric($boxContentListRecordFromForm['year_to_list']))
				//	handleError(TextHandler::getText('bxt_err_list_year_error'), $this->getListPageLink());
								
				$boxContentListRecordFromForm['sizemin'] = null;
				$boxContentListRecordFromForm['sizemax'] = null;
				$boxContentListRecordFromForm['box_article_ids'] = null;
				$boxContentListRecordFromForm['type'] = BOXCONTENTLIST_TYPE_FIXED;
			}
			elseif($boxContentListRecordFromForm['class'] == "CategoryBoxContentList")
			{
				//if (empty($boxContentListRecordFromForm['year_to_list']) || !is_numeric($boxContentListRecordFromForm['year_to_list']))
				//	handleError(TextHandler::getText('bxt_err_list_year_error'), $this->getListPageLink());
								
				$boxContentListRecordFromForm['sizemin'] = null;
				$boxContentListRecordFromForm['sizemax'] = null;
				$boxContentListRecordFromForm['box_article_ids'] = null;
				$boxContentListRecordFromForm['type'] = BOXCONTENTLIST_TYPE_FIXED;
			}
			*/
			// ok, save it back!
			try {
				$boxContentListRecordIndex = $this->getBoxContentListFromSession($boxContentListRecordId);
				$boxContentListRecord = $this->allBoxContentListRecords[$boxContentListRecordIndex];
				if(empty($boxContentListRecord['attributes']))
					$attributes = array();
				else
					$attributes = unserialize($boxContentListRecord['attributes']);
				foreach ($boxContentListRecordFromForm as $key => $value) {
					/*
					if($key == "bPerPage") {
						// ez attribútumban van!
						if(!empty($value) && TextUtil::isStringInteger($value))
							$attributes[BrandBoxContentList::ATTR_BRANDS_PER_PAGE] = intval($value);
						else
							unset($attributes[BrandBoxContentList::ATTR_BRANDS_PER_PAGE]);
					}
					elseif($key == "category") {
						if(!empty($value)) {
							// ez attribútumban van!
							$arr = explode("_", $value);
							$categoryId = $arr[0];
							$categoryType = $arr[1];
							if(!TextUtil::isStringInteger($categoryId))
								$categoryId = null;
							else
								$categoryId = intval($categoryId);
							$categoryType = intval($categoryType);
							$attributes[CategoryBoxContentList::ATTR_CAT_ID] = $categoryId;
							$attributes[CategoryBoxContentList::ATTR_CAT_TYPE] = $categoryType;
						} else {
							unset($attributes['category']);
						}
					}
					elseif($key == "display") {
						// ez attribútumban van!
						if(!empty($value))
							$attributes[CategoryBoxContentList::ATTR_DISPLAY] = $value;
						else
							unset($attributes[CategoryBoxContentList::ATTR_DISPLAY]);
					}
					else
					*/
						$boxContentListRecord[$key] = $value;
				}
				if(empty($attributes))
					$boxContentListRecord['attributes'] = null;
				else
					$boxContentListRecord['attributes'] = serialize($attributes);
				$boxContentListRecord['ismodified'] = true;
				if (empty($boxContentListRecord['autostep'])) {
					$boxContentListRecord['autostep'] = null;
				}
				$this->allBoxContentListRecords[$boxContentListRecordIndex] = $boxContentListRecord;
				$this->setBoxContentListRecords($this->allBoxContentListRecords);

				// session ürítése
				unset($_SESSION["_bxt_boxContentListId"]);
				unset($_SESSION["_bxt_isnew"]);
				FormUtil::removeFormInstanceIfExists("boxtabcontentlist", "saved");
				
				// ok, done!
				handleSuccess(TextHandler::getText("bxt_list_modified"), $this->getListPageLink());
				exit();

			} catch (MissingTableRowException $e2) {
				$errorStrings = array(TextHandler::getText('bxt_err_contentlistnotfound'));
				$logErrorString = "failed to update box_content_list record id=$boxContentListRecordId in db!";
			} catch (Exception $e2) {
				$errorStrings = array($e2->getMessage());
				$logErrorString = "failed to update box_content_list record id=$boxContentListRecordId in db!";
			}

		}
		else
		{
			$errorStrings = array(TextHandler::getText('bxt_err_contentlistnotfound'));
			$logErrorString = "failed to find box tab record id=$boxContentListRecordId in db, probably deleted";
		}

		Log::error('following errors occured during operation:'.$logErrorString);
		handleError(TextHandler::getParsedText('bxt_err_list_save_failed', array("errors"=>TextUtil::arrayToHtmlList($errorStrings))), $this->getListPageLink());
		exit();
	}

	/**
	 * Cancel
	 */
	private function action_cancelBoxContentList()
	{
		// session ürítése
		unset($_SESSION["_bxt_boxContentListId"]);
		FormUtil::removeFormInstanceIfExists("boxcontentlist", "saved");

		// visszalépünk a listára
		handleSuccess(null, $this->getListPageLink());
		exit();
	}

}
?>
